using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Models;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Extensions;

/// <summary>
/// 基础设施层配置映射扩展方法
/// </summary>
public static class InfrastructureConfigurationExtensions
{
    /// <summary>
    /// 添加配置映射服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置对象</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddConfigurationMapping(this IServiceCollection services, IConfiguration configuration)
    {
        // 注册基础 AppSettingsMapper
        services.AddSingleton(provider => new AppSettingsMapper(configuration));
        
        // 注册增强版 EnhancedAppSettingsMapper  
        services.AddSingleton(provider => new EnhancedAppSettingsMapper(configuration, provider.GetService<ILogger<EnhancedAppSettingsMapper>>()));
        
        // 注册基础 ConfigurationMappingFactory
        services.AddSingleton(provider => 
            new ConfigurationMappingFactory(configuration, provider.GetService<ILogger<ConfigurationMappingFactory>>()));

        // 注册增强版 EnhancedConfigurationMappingFactory
        services.AddSingleton(provider => 
            new EnhancedConfigurationMappingFactory(configuration, provider.GetService<ILogger<EnhancedConfigurationMappingFactory>>()));

        // 配置强类型配置对象
        ConfigureTypedConfigurations(services, configuration);

        // 添加配置验证
        AddConfigurationValidation(services);

        // 注册配置健康检查
        services.AddHealthChecks().AddCheck<ConfigurationHealthCheck>("configuration");

        return services;
    }

    /// <summary>
    /// 配置强类型配置对象
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置对象</param>
    private static void ConfigureTypedConfigurations(IServiceCollection services, IConfiguration configuration)
    {
        // 数据库配置
        services.Configure<DatabaseConfiguration>(config =>
        {
            configuration.Bind(config);
        });

        // 日志配置
        services.Configure<LoggingConfiguration>(configuration.GetSection("Logging"));
        services.Configure<SerilogCustConfiguration>(configuration.GetSection("SerilogCust"));
        services.Configure<SerilogConfiguration>(configuration.GetSection("Serilog"));

        // JWT配置
        services.Configure<JwtConfiguration>(configuration.GetSection("Jwt"));

        // 服务器配置
        services.Configure<ServerConfiguration>(configuration.GetSection("Server"));

        // 缓存设置配置
        services.Configure<CacheSettingsConfiguration>(configuration.GetSection("CacheSettings"));

        // 允许的主机配置 - 使用增强配置映射工厂
        services.Configure<AllowedHostsConfiguration>(config =>
        {
            var configFactory = new EnhancedConfigurationMappingFactory(configuration);
            var allowedHosts = configFactory.GetAllowedHostsConfiguration();
            config.Hosts = allowedHosts.Hosts;
        });

        // 添加配置验证
        AddConfigurationValidation(services);
    }

    /// <summary>
    /// 添加配置验证
    /// </summary>
    /// <param name="services">服务集合</param>
    private static void AddConfigurationValidation(IServiceCollection services)
    {
        // 移除 ValidateOptionsDataAnnotations，使用内置验证
        services.AddOptions<DatabaseConfiguration>().ValidateDataAnnotations();
        services.AddOptions<JwtConfiguration>().ValidateDataAnnotations();
        services.AddOptions<ServerConfiguration>().ValidateDataAnnotations();
        services.AddOptions<CacheSettingsConfiguration>().ValidateDataAnnotations();
    }

    /// <summary>
    /// 验证配置完整性
    /// </summary>
    /// <param name="serviceProvider">服务提供者</param>
    /// <returns>验证结果</returns>
    public static ConfigurationValidationResult ValidateConfigurations(this IServiceProvider serviceProvider)
    {
        var validationResult = new ConfigurationValidationResult();

        try
        {
            // 验证数据库配置
            var databaseConfig = serviceProvider.GetRequiredService<IOptionsMonitor<DatabaseConfiguration>>().CurrentValue;
            ValidateConfiguration(databaseConfig, "Database", validationResult);

            // 验证JWT配置
            var jwtConfig = serviceProvider.GetRequiredService<IOptionsMonitor<JwtConfiguration>>().CurrentValue;
            ValidateConfiguration(jwtConfig, "JWT", validationResult);

            // 验证服务器配置
            var serverConfig = serviceProvider.GetRequiredService<IOptionsMonitor<ServerConfiguration>>().CurrentValue;
            ValidateConfiguration(serverConfig, "Server", validationResult);

            // 验证缓存配置
            var cacheConfig = serviceProvider.GetRequiredService<IOptionsMonitor<CacheSettingsConfiguration>>().CurrentValue;
            ValidateConfiguration(cacheConfig, "Cache", validationResult);

            validationResult.IsValid = !validationResult.Errors.Any();
        }
        catch (Exception ex)
        {
            validationResult.Errors.Add($"Configuration validation failed: {ex.Message}");
            validationResult.IsValid = false;
        }

        return validationResult;
    }

    /// <summary>
    /// 验证单个配置对象
    /// </summary>
    /// <param name="configuration">配置对象</param>
    /// <param name="sectionName">配置节名称</param>
    /// <param name="validationResult">验证结果</param>
    private static void ValidateConfiguration(object configuration, string sectionName, ConfigurationValidationResult validationResult)
    {
        var validationContext = new ValidationContext(configuration);
        var validationResults = new List<ValidationResult>();

        if (!Validator.TryValidateObject(configuration, validationContext, validationResults, true))
        {
            foreach (var result in validationResults)
            {
                validationResult.Errors.Add($"{sectionName}: {result.ErrorMessage}");
            }
        }
    }

    /// <summary>
    /// 获取配置概要信息
    /// </summary>
    /// <param name="serviceProvider">服务提供者</param>
    /// <returns>配置概要</returns>
    public static ConfigurationSummary GetConfigurationSummary(this IServiceProvider serviceProvider)
    {
        var factory = serviceProvider.GetRequiredService<ConfigurationMappingFactory>();
        var databaseConfig = factory.GetDatabaseConfiguration();
        var serverConfig = factory.GetServerConfiguration();
        var jwtConfig = factory.GetJwtConfiguration();

        return new ConfigurationSummary
        {
            DatabaseType = databaseConfig.DatabaseType,
            Environment = serverConfig.Environment,
            ServerPort = serverConfig.Port,
            JwtExpiryMinutes = jwtConfig.ExpiryMinutes,
            ConfigurationLoadTime = DateTime.UtcNow
        };
    }
}

/// <summary>
/// 配置验证结果
/// </summary>
public class ConfigurationValidationResult
{
    public bool IsValid { get; set; } = true;
    public List<string> Errors { get; set; } = new();
    public List<string> Warnings { get; set; } = new();
}

/// <summary>
/// 配置概要信息
/// </summary>
public class ConfigurationSummary
{
    public string DatabaseType { get; set; } = string.Empty;
    public string Environment { get; set; } = string.Empty;
    public int ServerPort { get; set; }
    public int JwtExpiryMinutes { get; set; }
    public DateTime ConfigurationLoadTime { get; set; }
}
